import { createRouter, createWebHistory } from 'vue-router';

import LoginPage from '../views/LoginPage.vue';
import RegisterPage from '../views/RegisterPage.vue';
import TestPage from '../views/TestPage.vue';
import ResultPage from '../views/ResultPage.vue';
import StudentsPage from '../views/StudentManagement.vue';
import MajorsPage from '../views/MajorsManagement.vue';
import CollegesPage from '../views/CollegesManagementPage.vue';
import ClazzPage from '../views/ClazzManagement.vue';
import NotFound from '../views/NotFound.vue';

const routes = [
    { path: '/login', component: LoginPage },
    { path: '/register', component: RegisterPage },
    { path: '/test', component: TestPage },
    { path: '/result', component: ResultPage },
    { path: '/students', component: StudentsPage },
    { path: '/majors', component: MajorsPage },
    { path: '/colleges', component: CollegesPage },
    { path: '/clazz', component: ClazzPage },
    { path: '/', redirect: '/test' },
    { path: '/:catchAll(.*)', component: NotFound },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    const isLoggedIn = !!sessionStorage.getItem('loggedIn'); // 改用 sessionStorage 判断登录态
    if ((to.path !== '/login' && to.path !== '/register') && !isLoggedIn) {
        next('/login');
    } else {
        next();
    }
});

export default router;
